package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 通过反射机制调出方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws Exception {
        /*
        //1.实例化Class类对象
        Class cls = Class.forName("reflect.Person");
        //2.调用无参构造方法实例化Person对象, 相当于: Object obj = new Person();
        Object obj = cls.newInstance();
        //3.通过类对象获取sayHello方法
        Method method = cls.getMethod("sayHello");
        //4.通过方法对象的invoke来调用sayHello方法, 掺入的参数为方法的所属对象, 相当于: obj.sayHello();
        method.invoke(obj);
         */

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个类名");
        String className = scan.nextLine();
        System.out.println("请输入一个方法名:");
        String methodName = scan.nextLine();

        Class cls = Class.forName(className);
        Constructor c = cls.getConstructor(String.class);
        Object obj = cls.newInstance();
        Method method = cls.getMethod(methodName);
        method.invoke(obj);
    }
}
